//
//  CZQCycleDetalVC.m
//  coachmanage
//
//  Created by 众拳科技 on 2018/3/23.
//  Copyright © 2018年 众拳科技. All rights reserved.
//

#import "CZQCycleDetalVC.h"
#import "CZQHomeVIPCommentCell.h"
#import "CZQCycleSectionHeadView.h"
#import "HDAlertView.h"
#import "DHChatToolView.h"
#import "CZQGoodListVC.h"
@interface CZQCycleDetalVC ()<UITableViewDelegate,UITableViewDataSource,DHChatToolViewDelegate,UIScrollViewDelegate>
/**
 //数据源
 */
@property(nonatomic,strong)NSMutableArray *dataArr;

/**
 点赞列表数据源
 */
@property(nonatomic,strong)NSMutableArray *goodDataArr;

/**
 tableView
 */
@property(nonatomic,weak)UITableView *tableView;

@property(nonatomic,strong)NoDataView *noDataView;


/**
 //输入评论面板
 */
@property(nonatomic,weak)DHChatToolView *toolView;

/**
 senctionHead
 */
@property(nonatomic,weak)CZQCycleSectionHeadView *senctionHead;

@property(nonatomic,assign)NSInteger index;

@property(nonatomic,assign)NSInteger pageSize;
@end

@implementation CZQCycleDetalVC

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"圈子详情";
    
    [self tableView];
    
    [self getGoodList];
}


#pragma mark 下拉
-(void)loadStartData{
    
    self.index = 1;
    
    self.pageSize = 20;
    
    [self loadData];
}

#pragma mark 上拉
-(void)loadMoreData{
    
    self.index = self.index + 1;
    
    [self loadData];
}

#pragma mark - 获取点赞列表
-(void)getGoodList
{
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    NSString *userId = [[NSUserDefaults standardUserDefaults] valueForKey:@"UserID"];
    
    
    
    [params setValue:self.cycleModel.ID forKey:@"ActivityID"];
    [params setValue :@"1" forKey:@"page"];
    [params setValue :@"5" forKey:@"rows"];
    
    
    [HTTPTool GET:Get_Activity_GetActivityVoteList parameters:params
     
          success:^(id responseObject){
              
              [MBProgressHUD hideHUDForView:self.view];
              
              NSLog(@"%@=%@",responseObject,userId);
              
              if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                  
                  NSArray *resultArray = [responseObject objectForKey:@"rows"];
                  
                  if (resultArray.count == 0) {
                      return ;
                  }
                  
                  [self.goodDataArr addObjectsFromArray:resultArray];
                  
                  
                  [self.tableView reloadData];
                  
                  
              }
              
          }
     
          failure:^(NSError *error){
              
              [self.tableView.mj_header endRefreshing];
              
              [MBProgressHUD hideHUDForView:self.view];
          }];
}

-(void)loadData{
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [params setObject:[NSString stringWithFormat:@"%d",self.index] forKey:@"page"];
    
    [params setObject:[NSString stringWithFormat:@"%d",self.pageSize] forKey:@"rows"];
    
    ;
    
    [params setObject:self.cycleModel.ID forKey:@"ActivityID"];
    
    
    [MBProgressHUD showMessage:@"请求中..." toView:self.view];
    
    [HTTPTool GET:GET_Activity_CommentList parameters:params
     
          success:^(id responseObject){
              
              [MBProgressHUD hideHUDForView:self.view];
              
              NSLog(@"%@",responseObject);
              
              if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                  
                  NSArray *resultArray = [responseObject objectForKey:@"rows"];
                  
                  
                  if (resultArray.count > 0) {
                      
                      [self.tableView.mj_header endRefreshing];
                      
                      [self.tableView.mj_footer endRefreshing];
                  }
                  else{
                      
                      [self.tableView.mj_header endRefreshing];
                      
                      [self.tableView.mj_footer endRefreshingWithNoMoreData];
                  }
                  
                  if (self.index == 1) {
                      [self.dataArr removeAllObjects];
                  }
                  
                  
                  
                  
                  for (NSDictionary *resultDic in resultArray) {
                      
                      CZQCycleCommentModel *comment = [CZQCycleCommentModel mj_objectWithKeyValues:resultDic];
                      
                      [self.dataArr addObject:comment];
                      
                  }
//                  self.noDataView = [NoDataView shareInstance];
//
//                  [self.noDataView hideInView:self.view];
//
//                  if (self.dataArr.count == 0) {
//
//                      self.noDataView = [NoDataView shareInstance];
//
//                      [self.noDataView showInView:self.view];
//                  }
                  
                  [MBProgressHUD hideHUDForView:self.view];
                  
                  [self.tableView reloadData];
              }
              
          }
     
          failure:^(NSError *error){
              
              [self.tableView.mj_header endRefreshing];
              
              [MBProgressHUD hideHUDForView:self.view];
          }];
}


#pragma mark -- 懒加载

-(DHChatToolView *)toolView
{
    if (!_toolView) {
        
        DHChatToolView *toolView = [[DHChatToolView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height, kScreenWidth, 49)];
        //底部回复
        _toolView = toolView;
        _toolView.backgroundColor = [UIColor whiteColor];
        _toolView.msgTextView.returnKeyType = UIReturnKeySend;
        _toolView.msgTextView.font = [UIFont systemFontOfSize:15];
//        _toolView.msgText/View.placeLable.text = @"评论:";
        [self.view addSubview:_toolView];
        
        _toolView.delegate = self;
        
        _toolView.isHidVoiceBtn = YES;
        _toolView.addBtn.hidden = YES;
        _toolView.isHidSendBtn = NO;
        _toolView.isHidFaceBtn = YES;
        
    }
    return _toolView;
}

-(NSMutableArray *)dataArr
{
    if (!_dataArr) {
        
        _dataArr = [NSMutableArray array];
        
    }
    
    return _dataArr;
}

-(NSMutableArray *)goodDataArr
{
    if (!_goodDataArr) {
        
        _goodDataArr = [NSMutableArray array];
        
    }
    
    return _goodDataArr;
}

-(UITableView *)tableView
{
    if (!_tableView) {
        
        UITableView *tableView=[[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        
        tableView.delegate=self;
        
        tableView.dataSource=self;
        
        tableView.backgroundColor = BackGroundColor;
        
        tableView.estimatedRowHeight = 150;
        
        [self.view addSubview:tableView];
        
        [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.edges.mas_equalTo(self.view);
            
        }];
        
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        
        //注册
        [tableView registerClass:[DHCycleTableViewCell class] forCellReuseIdentifier:@"cell"];
        
        [tableView registerClass:[CZQHomeVIPCommentCell class] forCellReuseIdentifier:@"comment"];
        
        
        _tableView = tableView;
        
        MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        footer.automaticallyHidden = YES;
        
        
        MyTableHead *mj_head = [MyTableHead headerWithRefreshingTarget:self refreshingAction:@selector(loadStartData)];
        tableView.mj_header = mj_head;
        tableView.mj_footer = footer;
        [tableView.mj_header beginRefreshing];
        
    }
    return _tableView;
}

#pragma mark - UITableViewDataSource

//行数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

//列数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    return self.dataArr.count;
}

//cell内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        DHCycleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        //举报
        cell.reportBtn.hidden = NO;
        [cell.reportBtn addTarget:self action:@selector(report)];
        cell.sexBtn.hidden = NO;
        cell.clubNameBtn.hidden = YES;
//        [cell.seeBtn setImage:@""]
        cell.talkBtn.hidden = YES;
        
        //关注
        [cell.seeBtn addTarget:self action:@selector(like)];
        
        //评论
        [cell.goodBtn setImage:@"icon_comment"];
        [cell.goodBtn addTarget:self action:@selector(comment)];
        
        [cell.iconBtn sd_setImageWithURL:[NSURL URLWithString:[Helper imageUrlStringToChinese:self.cycleModel.Pic imageType:nil]] forState:UIControlStateNormal placeholderImage:PlaceHold];
        
        cell.nameLable.text = self.cycleModel.Name;
        
        cell.timeLable.text = self.cycleModel.PostTime;
        
        [cell.clubNameBtn setTitle:self.cycleModel.ShopName];
        
        cell.clubNameBtn.hidden =  self.cycleModel.ShopName.length > 0?NO:YES;
        
        cell.contentLable.text = self.cycleModel.Title;
        
        [cell.sexBtn setImage: [self.cycleModel.Sex intValue] == 0?@"icon_man":@"icon_women"];
        [cell.sexBtn setTitle:@""];
        
        
        if (self.cycleModel.Pics.length > 0) {
            
            NSArray *picArr = [self.cycleModel.Pics componentsSeparatedByString:@","];
            ///布局九宫格
            [cell.jggView JGGView:cell.jggView DataSource:picArr completeBlock:^(NSInteger index, NSArray *dataSource,NSIndexPath *indexpath) {
                
                
                
            }];
        }
        
//        [cell.sexBtn setTitle:[NSString stringWithFormat:@"%@ ",self.cycleModel.ActivityCount]];
        
//        [cell.talkBtn setTitle:[NSString stringWithFormat:@"%@ ",self.cycleModel.CommentCount]];
        
//        [cell.goodBtn setTitle:[NSString stringWithFormat:@"%@ ",self.cycleModel.CommentCount]];
        
        return cell;
    }
    CZQHomeVIPCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"comment"];
    
    CZQCycleCommentModel *model = [self.dataArr objectAtIndex:indexPath.row];
    
    [cell.iconBtn sd_setImageWithURL:[NSURL URLWithString:[Helper imageUrlStringToChinese:model.MemberPic imageType:nil]] forState:UIControlStateNormal placeholderImage:PlaceHold];
    cell.nameLable.text = model.MemberName;
    cell.timeLable.text = model.AddTime;
    cell.titleLable.text = model.Message;
    
    cell.starView.hidden = YES;
    
    return cell  ;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return CGFLOAT_MIN;
    }
    return 130;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.00001;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [[UIView alloc]initWithFrame:CGRectZero];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section !=0) {
        
        CZQCycleSectionHeadView *senctionHead = [CZQCycleSectionHeadView new];
        
        self.senctionHead = senctionHead;
        
         WS(weakSelf);
        
        if (self.goodDataArr.count > 0) {
            
            senctionHead.goodArrM = self.goodDataArr;
            
            //跳转点赞列表
            [senctionHead.scrollView bk_removeAllBlockObservers];
            
            [senctionHead.scrollView bk_whenTapped:^{
                
                CZQGoodListVC *good = [CZQGoodListVC new];
                
                good.ID = weakSelf.cycleModel.ID;
                
                good.title = @"加油";
                
                [weakSelf.navigationController pushViewController:good animated:YES];
                
            }];
            
        }
        
       
        
        
        
        
        senctionHead.goodCiunLable.text = [NSString stringWithFormat:@"已有%@人点赞 ",self.cycleModel.VoteCount];
        
        senctionHead.commentCountLable.text = [NSString stringWithFormat:@"共%ld条评论",self.dataArr.count];
        
        return senctionHead;
        
    }
    return [[UIView alloc]initWithFrame:CGRectZero];
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //当离开某行时，让某行的选中状态消失
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

#pragma mark - 关注
-(void)like
{
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    
    [params setObject:[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"UserID"]] forKey:@"MemberID"];
    
    [params setObject:[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"MasterType"]] forKey:@"UserType"];
    

    
    [params setObject:self.cycleModel.MemberID forKey:@"ToMemberID"];
    
    [params setObject:self.cycleModel.UserType forKey:@"ToUserType"];
    
    
    
    
    
    [MBProgressHUD showMessage:@"请求中..." toView:self.view];
    
    
    
    [HTTPTool POSTRaw:Post_Activity_FollowOperate parameters:params
     
              success:^(id responseObject){
                  
                  [MBProgressHUD hideHUDForView:self.view];
                  
                  if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                      
                      [MBProgressHUD showText:@"关注成功"];
                      
                      self.cycleModel.ActivityCount = [NSString stringWithFormat:@"%ld",[self.cycleModel.ActivityCount integerValue] + 1 ];
                      
                      NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:0];
                      
                      [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationFade];
                      
                      
                      [MBProgressHUD hideHUDForView:self.view];
                  }
                  
              }
     
              failure:^(NSError *error){
                  
                  [MBProgressHUD hideHUDForView:self.view];
              }];
    
}

#pragma mark - 举报
-(void)report
{
    [JHSysAlertUtil presentAlertWithTitle:nil message:nil actionTitles:@[@"举报"] preferredStyle:UIAlertControllerStyleActionSheet handler:^(NSUInteger buttonIndex, NSString *buttonTitle) {
        
        if (buttonIndex == 1) {
            [JHSysAlertUtil presentAlertWithTitle:nil message:nil actionTitles:@[@"色情 裸露",@"不友善行为",@"广告推销",@"其他"] preferredStyle:UIAlertControllerStyleActionSheet handler:^(NSUInteger buttonIndex, NSString *buttonTitle) {
                
                if (buttonIndex == 0) {
                    return ;
                }
                
                NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
                
                
                [params setObject:[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"UserID"]] forKey:@"MemberID"];
              
                [params setObject:self.cycleModel.ID forKey:@"ActivityID"];
                
                [params setObject:buttonTitle forKey:@"Message"];
                
//                [params setObject:buttonTitle forKey:@"Message"];
                
                
                
                
                
                [MBProgressHUD showMessage:@"请求中..." toView:self.view];
                
                
                
                [HTTPTool POSTRaw:Post_Activity_ReportOperate parameters:params
                 
                          success:^(id responseObject){
                              
                              [MBProgressHUD hideHUDForView:self.view];
                              
                              if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                                  
                                  [MBProgressHUD showText:@"举报成功"];
                                  
                                  self.cycleModel.ActivityCount = [NSString stringWithFormat:@"%ld",[self.cycleModel.ActivityCount integerValue] + 1 ];
                                
                                  
                                  
                                  [MBProgressHUD hideHUDForView:self.view];
                              }
                              
                          }
                 
                          failure:^(NSError *error){
                              
                              [MBProgressHUD hideHUDForView:self.view];
                          }];
                
                
            }];
        }
        
        
        
    }];
    
    
}

#pragma mark - 评论
-(void)chatToolViewClickSend
{
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    
    [params setObject:[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"UserID"]] forKey:@"MemberID"];
    
    [params setObject:[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"MasterType"]] forKey:@"UserType"];
    
    [params setObject:self.cycleModel.ID forKey:@"ActivityID"];
    
    NSString *title = self.toolView.msgTextView.text;
    
    [params setObject:title forKey:@"Message"];
    
    [params setObject:self.cycleModel.MemberID forKey:@"ReplyTo"];
    
    [params setObject:self.cycleModel.UserType forKey:@"ToUserType"];
    
    
    
    
    
    [MBProgressHUD showMessage:@"请求中..." toView:self.view];
    
    
    
    [HTTPTool POSTRaw:Post_Activity_CommentOperate parameters:params
     
              success:^(id responseObject){
                  
                  [MBProgressHUD hideHUDForView:self.view];
                  
                  if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                      
                      [MBProgressHUD showText:@"评论成功"];
                      
                      [self loadData];
                      
                      
                      [MBProgressHUD hideHUDForView:self.view];
                  }
                  
              }
     
              failure:^(NSError *error){
                  
                  [MBProgressHUD hideHUDForView:self.view];
              }];
    
}


-(void)comment
{
//    self.toolView.msgTextView.placeLable.text = @"评论:";
    [self.toolView.msgTextView becomeFirstResponder];
    
}

#pragma mark -- scrollViewDelegate

-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    [self hidKeyorLikeView];
}




//隐藏键盘，和点赞评论面板
-(void)hidKeyorLikeView
{
    [_toolView hidFaceView];
    
    [self.view endEditing:YES];
    
    [self.view layoutIfNeeded];
    [self.view setNeedsUpdateConstraints];
    [self.view updateConstraintsIfNeeded];
    
    
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
    [IQKeyboardManager sharedManager].enable = NO;
    
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
    
    [IQKeyboardManager sharedManager].enable = YES;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
